package com.hui.server.filter;

import com.hui.server.entity.Menu;
import com.hui.server.entity.Role;
import com.hui.server.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.*;

/**
 * @BelongsProject: yeb
 * @BelongsPackage: com.hui.server.config.filter
 * @Author: HUI
 * @CreateTime: 2022-04-07 09:54
 * @Description: 权限控制：根据请求的URL获取所对应需要的角色role
 */
@Component
@Slf4j
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private MenuService menuService;

    //SpringBoot 工具类
    AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        log.info("访问的路径requestUrl :{} ", requestUrl);

        //获取所有角色拥有的菜单
        List<Menu> menus = menuService.getMenusByRoles();
        log.info("获取到所有角色的menu菜单，数量为：{}", menus.size());

        for (Menu menu : menus) {

            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);

                //传递的是需要的角色数组
                log.info("获取到访问该URL所需的权限数量：{}", str.length);
                return SecurityConfig.createList(str);

            }
        }

        return null;
    }


    //这样写会拦截swagger
    /*@Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        log.info("访问的路径requestUrl :{} ", requestUrl);

        //获取菜单
        List<Menu> menus = menuService.getMenusByRoles();
        log.info("获取到所有角色的menu菜单，数量为：{}",menus.size());
        for (Menu menu : menus) {
            //判断请求的url与菜单角色是否匹配
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                //System.out.println("menu = " + menu.getUrl());
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);

                //传递的是需要的角色数组
                return SecurityConfig.createList(str);
            }
        }
        //没匹配的url默认为登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");

    }*/


    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
